"use strict";

module.exports = core;

const colors = require("colors/safe");
const commander = require("commander");

const log = require("@azir-cli/log");
const exec = require("@azir-cli/exec");

const prepare = require("./prepare");
const pkg = require("../package.json");

async function core() {
  try {
    await prepare();
    // 注册命令
    registerCommand();
  } catch (e) {
    log.error(e.message);
    console.error(e);
  }
}

/**
 * 注册命令
 */
const program = new commander.Command();

function registerCommand() {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage("<command> [options]")
    .version(pkg.version)
    .option("-d, --debug", "是否开启debug模式", false)
    .option("-tp, --targetPath <targetPath>", "本地调试文件路径", "");

  program
    .command("init [projectName]")
    .option("-f, --force", "是否强制初始化项目")
    .action(exec);

  program.on("option:debug", onDebugArg);
  program.on("option:targetPath", onTargetPath);
  program.on("command:*", onUnknownCommand);

  if (!process.argv[2]) {
    program.outputHelp();
  }

  program.parse(process.argv);
}
/**
 * 输入 targetPath 时，将其存入到环境变量
 */
function onTargetPath() {
  process.env.AZIR_CLI_TARGET_PATH = program.opts().targetPath;
}
/**
 * 未知命令
 */
function onUnknownCommand(args) {
  const availableCommands = program.commands.map((c) => c.name());
  console.log(colors.red(`未知的命令: ${args[0]}`));
  if (availableCommands.length > 0) {
    console.log(colors.green(`可用的命令: ${availableCommands.join(", ")}`));
  }
}

/**
 * 检查debug入参
 */
function onDebugArg() {
  process.env.LOG_LEVEL = "verbose";
  log.level = process.env.LOG_LEVEL;
  {
    log.debug("using debug mode");
  }
}
